{% extends "base.html" %}

{% block title %}数据统计 - 梦幻西游数字资产管理系统{% endblock %}

{% block mobile_title %}数据统计{% endblock %}

{% block content %}
<div class="container-fluid statistics-page">
    <div class="row mb-4">
        <div class="col-12">
            <h2 class="page-title">📊 数据统计分析</h2>
        </div>
    </div>
    
    <!-- 统计卡片 -->
    <div class="row mb-4">
        <div class="col-md-3 col-6 mb-3">
            <div class="stat-card">
                <i class="bi bi-people stat-icon text-primary"></i>
                <div class="stat-value" id="totalAccounts">-</div>
                <div class="stat-label">总账号数</div>
            </div>
        </div>
        <div class="col-md-3 col-6 mb-3">
            <div class="stat-card">
                <i class="bi bi-person-circle stat-icon text-info"></i>
                <div class="stat-value" id="totalRoles">-</div>
                <div class="stat-label">总角色数</div>
            </div>
        </div>
        <div class="col-md-3 col-6 mb-3">
            <div class="stat-card">
                <i class="bi bi-check-circle stat-icon text-success"></i>
                <div class="stat-value" id="todayCompletion">-</div>
                <div class="stat-label">今日完成率</div>
            </div>
        </div>
        <div class="col-md-3 col-6 mb-3">
            <div class="stat-card">
                <i class="bi bi-calendar-check stat-icon text-warning"></i>
                <div class="stat-value" id="weekCompletion">-</div>
                <div class="stat-label">本周平均完成率</div>
            </div>
        </div>
    </div>
    
    <!-- 图表区域 -->
    <div class="row">
        <div class="col-lg-6 mb-4">
            <div class="card">
                <div class="card-header">
                    <i class="bi bi-bar-chart me-2"></i>账号类型分布
                </div>
                <div class="card-body">
                    <canvas id="accountTypeChart" height="200"></canvas>
                </div>
            </div>
        </div>
        
        <div class="col-lg-6 mb-4">
            <div class="card">
                <div class="card-header">
                    <i class="bi bi-pie-chart me-2"></i>角色门派分布
                </div>
                <div class="card-body">
                    <canvas id="factionChart" height="200"></canvas>
                </div>
            </div>
        </div>
        
        <div class="col-12 mb-4">
            <div class="card">
                <div class="card-header">
                    <i class="bi bi-graph-up me-2"></i>近7天任务完成趋势
                </div>
                <div class="card-body">
                    <canvas id="trendChart" height="100"></canvas>
                </div>
            </div>
        </div>
        
        <div class="col-lg-6 mb-4">
            <div class="card">
                <div class="card-header">
                    <i class="bi bi-trophy me-2"></i>角色等级分布
                </div>
                <div class="card-body">
                    <div id="levelDistribution"></div>
                </div>
            </div>
        </div>
        
        <div class="col-lg-6 mb-4">
            <div class="card">
                <div class="card-header">
                    <i class="bi bi-star me-2"></i>活跃角色排行 Top10
                </div>
                <div class="card-body">
                    <div id="activeRanking"></div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.3.0/dist/chart.umd.min.js"></script>
<script>
let accountTypeChart = null;
let factionChart = null;
let trendChart = null;

$(document).ready(function() {
    loadStatistics();
    loadAccountTypeChart();
    loadFactionChart();
    loadTaskTrendChart();
    loadLevelDistribution();
    loadActiveRoles();
});

// 加载统计概览
async function loadStatistics() {
    try {
        const data = await apiRequest('/api/statistics/overview');
        const stats = data.data;
        
        $('#totalAccounts').text(stats.account_count);
        $('#totalRoles').text(stats.role_count);
        $('#todayCompletion').text(stats.today_completion_rate + '%');
        $('#weekCompletion').text(stats.week_completion_rate + '%');
    } catch (error) {
        console.error('加载统计数据失败:', error);
        showNotification('加载统计数据失败', 'error');
    }
}

// 加载账号类型分布图
async function loadAccountTypeChart() {
    try {
        const data = await apiRequest('/api/statistics/account-types');
        const chartData = data.data;
        
        if (chartData.labels.length === 0) {
            return;
        }
        
        const ctx = document.getElementById('accountTypeChart').getContext('2d');
        
        if (accountTypeChart) {
            accountTypeChart.destroy();
        }
        
        accountTypeChart = new Chart(ctx, {
            type: 'bar',
            data: {
                labels: chartData.labels,
                datasets: [{
                    label: '账号数量',
                    data: chartData.data,
                    backgroundColor: [
                        'rgba(102, 126, 234, 0.8)',
                        'rgba(118, 75, 162, 0.8)',
                        'rgba(52, 152, 219, 0.8)',
                        'rgba(46, 204, 113, 0.8)',
                        'rgba(241, 196, 15, 0.8)'
                    ]
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: { display: false }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: {
                            stepSize: 1
                        }
                    }
                }
            }
        });
    } catch (error) {
        console.error('加载账号类型图表失败:', error);
    }
}

// 加载门派分布饼图
async function loadFactionChart() {
    try {
        const data = await apiRequest('/api/statistics/factions');
        const chartData = data.data;
        
        if (chartData.labels.length === 0) {
            return;
        }
        
        const ctx = document.getElementById('factionChart').getContext('2d');
        
        if (factionChart) {
            factionChart.destroy();
        }
        
        const colors = [
            '#FF6384', '#36A2EB', '#FFCE56', '#4BC0C0', '#9966FF',
            '#FF9F40', '#FF6384', '#C9CBCF', '#4BC0C0', '#FF6384',
            '#36A2EB', '#FFCE56', '#9966FF', '#FF9F40', '#C9CBCF'
        ];
        
        factionChart = new Chart(ctx, {
            type: 'doughnut',
            data: {
                labels: chartData.labels,
                datasets: [{
                    data: chartData.data,
                    backgroundColor: colors.slice(0, chartData.labels.length)
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'right'
                    }
                }
            }
        });
    } catch (error) {
        console.error('加载门派分布图表失败:', error);
    }
}

// 加载任务完成趋势图
async function loadTaskTrendChart() {
    try {
        const data = await apiRequest('/api/statistics/task-trend');
        const chartData = data.data;
        
        const ctx = document.getElementById('trendChart').getContext('2d');
        
        if (trendChart) {
            trendChart.destroy();
        }
        
        trendChart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: chartData.labels,
                datasets: [{
                    label: '任务完成率 (%)',
                    data: chartData.data,
                    borderColor: 'rgb(102, 126, 234)',
                    backgroundColor: 'rgba(102, 126, 234, 0.1)',
                    tension: 0.4,
                    fill: true
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    y: {
                        beginAtZero: true,
                        max: 100,
                        ticks: {
                            callback: function(value) {
                                return value + '%';
                            }
                        }
                    }
                }
            }
        });
    } catch (error) {
        console.error('加载任务趋势图表失败:', error);
    }
}

// 加载角色等级分布
async function loadLevelDistribution() {
    try {
        const data = await apiRequest('/api/statistics/level-distribution');
        const stats = data.data;
        
        if (stats.length === 0) {
            $('#levelDistribution').html('<p class="text-center text-muted py-4">暂无数据</p>');
            return;
        }
        
        let html = '<div class="table-responsive"><table class="table table-sm">';
        html += '<thead><tr><th>等级范围</th><th class="text-end">角色数</th></tr></thead><tbody>';
        
        stats.forEach(stat => {
            html += `
                <tr>
                    <td>${stat.range}</td>
                    <td class="text-end"><strong>${stat.count}</strong></td>
                </tr>
            `;
        });
        
        html += '</tbody></table></div>';
        $('#levelDistribution').html(html);
    } catch (error) {
        console.error('加载等级分布失败:', error);
        $('#levelDistribution').html('<p class="text-center text-danger py-4">加载失败</p>');
    }
}

// 加载活跃角色排行
async function loadActiveRoles() {
    try {
        const data = await apiRequest('/api/statistics/active-roles');
        const roles = data.data;
        
        if (roles.length === 0) {
            $('#activeRanking').html('<p class="text-center text-muted py-4">暂无数据</p>');
            return;
        }
        
        let html = '<div class="table-responsive"><table class="table table-sm">';
        html += '<thead><tr><th>排名</th><th>角色名</th><th>门派</th><th>等级</th><th class="text-end">完成任务数</th></tr></thead><tbody>';
        
        roles.forEach(role => {
            const rankBadge = role.rank <= 3 ? 
                `<span class="badge bg-warning">${role.rank}</span>` : 
                `<span class="badge bg-secondary">${role.rank}</span>`;
            
            html += `
                <tr>
                    <td>${rankBadge}</td>
                    <td><strong>${role.role_name}</strong></td>
                    <td>${role.role_faction}</td>
                    <td>Lv.${role.role_level}</td>
                    <td class="text-end"><strong class="text-success">${role.completed_count}</strong></td>
                </tr>
            `;
        });
        
        html += '</tbody></table></div>';
        $('#activeRanking').html(html);
    } catch (error) {
        console.error('加载活跃角色失败:', error);
        $('#activeRanking').html('<p class="text-center text-danger py-4">加载失败</p>');
    }
}
</script>

<style>
.stat-card {
    background: white;
    border-radius: 8px;
    padding: 20px;
    text-align: center;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    transition: transform 0.2s;
}

.stat-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 4px 8px rgba(0,0,0,0.15);
}

.stat-icon {
    font-size: 2.5rem;
    margin-bottom: 10px;
}

.stat-value {
    font-size: 2rem;
    font-weight: bold;
    color: #333;
    margin: 10px 0;
}

.stat-label {
    color: #666;
    font-size: 0.9rem;
}
</style>
{% endblock %}